package com.group.transaction.config;

import com.group.transaction.util.StringUtil;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;

/**
 * SessionManager的类对应的使用环境：
 * DefaultSessionManager --> 默认实现，常用于javase
 * ServletContainerSessionManager --> 常用于web环境，单体web应用
 * DefaultWebSessionManager --> 常用于自定义实现
 *
 * @author YunXing Pang
 * @date 2019/7/28
 */
public class CustomSessionManager extends DefaultWebSessionManager {

    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        String sessionId = WebUtils.toHttp(request).getHeader("token");
        if (StringUtil.isEmpty(sessionId)) {
            return super.getSessionId(request, response);
        }
        request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, "cookie");
        request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, sessionId);
        request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
        return sessionId;
    }

}
